package com.shigen.demo.util;

import com.shigen.demo.entity.Result;
import com.shigen.demo.entity.User;
import java.lang.reflect.Field;

/**
 * @author shigenfu
 * @date /11/26 16:20
 */
public class ObjectUtil {

    /**
     * 把对象中的 String 类型的null字段，转换为空字符串
     *
     * @param <T>       待转化对象类型
     * @param object    待转化对象
     * @param fieldName 字段名字
     */
    public static <T> void noNullStringAttr(T object, String fieldName) {
        Field[] fields = object.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(object);
                    if (value == null && field.getName().equals(fieldName)) {
                        field.set(object, "");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        // 构造参数：status, msg, data
        Result<Object> result = new Result<>(200, null, null);
        ObjectUtil.noNullStringAttr(result, "msg");
        System.out.println(result);

        User user = new User().setUsername("abc").setPassword(null);
        ObjectUtil.noNullStringAttr(user, "password");
        System.out.println(user);

        ObjectUtil.noNullStringAttr(user, "username");
        System.out.println(user);
    }

}
